﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AlexandriaPressUserDataAccessLayer;
using AlexandriaPressUserObject;
using AlexandriaPressAuthorObject;
using System.Data;
using System.IO;
using System.Web.Security;
using System.Web;

namespace AlexandriaPressUserBusinessLayer
{
    public class UserBusinsessLayer
    {
        public static int findUnique(OrderItems addedFrom, OrderItems addedTo, ref bool unique)
        {
            if (addedFrom.BookID == addedTo.BookID)
            {
                addedTo.Quantity += addedFrom.Quantity;
                unique = false;              
            }

            return addedTo.Quantity;
        }

        //create user
        public void createUser(string firstname, string lastname, string gender, string email, DateTime birthday, DateTime datejoined, string deliveryadd, string username, string password, string question, string answer)
        {
            UserDataAccess.createUser(firstname, lastname, gender, email, birthday, datejoined, deliveryadd, username, password, question, answer);
        }

        public int uniqueUsername(string username)
        {
            return UserDataAccess.checkUniqueUsername(username);
        }

        public int uniqueEmail(string email)
        {
            return UserDataAccess.checkUniqueEmail(email);
        }

        public DateTime checkIfSuspended(int userID)
        {
            return UserDataAccess.checkIfSuspended(userID);
        }

        public int checkIfBanned(int userID)
        {
            return UserDataAccess.checkIfBanned(userID);
        }

        public string getUserType(string username)
        {
            return UserDataAccess.getUserType(username);
        }

        //get user
        public User getUser(string username)
        {
            return UserDataAccess.getUser(username);
        }

        public bool validateUser(string username, string password)
        {
            return UserDataAccess.ValidateUser(username, password);
        }

        public bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            return UserDataAccess.ChangePassword(username, oldPassword, newPassword);
        }

        public string ResetPassword(string username, string answer)
        {
            return UserDataAccess.ResetPassword(username, answer);
        }

        //transactions
        public List<Book> myTransactions(string username)
        {
            return UserDataAccess.myTransactions(username);
        }


        //profile

        public List<User> myProfile(string username)
        {
            return UserDataAccess.myProfile(username);
        }

        public DataTable profileView(List<User> profDetails)
        {
            DataTable table = new DataTable();
            table.Columns.Add("ProfilePicture");
            table.Columns.Add("FirstName");
            table.Columns.Add("LastName");
            table.Columns.Add("Gender");
            table.Columns.Add("Email");
            table.Columns.Add("Birthday");
            table.Columns.Add("DateJoined");
            table.Columns.Add("DeliveryAdd");

            foreach (User info in profDetails)
            {
                table.Rows.Add(info.ProfilePicture, info.FirstName, info.LastName, info.Gender, info.Email, info.Birthday, info.DateJoined, info.DeliveryAdd);
            }

            return table;
        }

        public DataTable transView(List<Book> transList)
        {
            DataTable table = new DataTable();
            table.Columns.Add("BookCover");
            table.Columns.Add("Title");
            table.Columns.Add("Author");
            table.Columns.Add("Genre");
            table.Columns.Add("Quantity");
            table.Columns.Add("PricePerUnit");
            table.Columns.Add("DateOfTransaction");

            foreach (Book trans in transList)
            {
                table.Rows.Add(trans.BookCover, trans.Title, trans.Author, trans.Genre, trans.Quantity, trans.PricePerUnit, trans.DateOfTransaction);
            }

            return table;
        }

        public DataTable searchTitleView(List<Book> searchItem)
        {
            DataTable table = new DataTable();
            table.Columns.Add("BookCover");
            table.Columns.Add("Title");
            table.Columns.Add("Author");
            table.Columns.Add("Genre");
            table.Columns.Add("QuantityInStock");
            table.Columns.Add("Price");
            table.Columns.Add("ID");
            foreach (Book book in searchItem)
            {
                table.Rows.Add(book.BookCover, book.Title, book.Author, book.Genre, book.QuantityInStock, book.PricePerUnit, book.BookID);
            }

            return table;
        }

        public DataTable searchAuthorView(List<User> searchItem)
        {
            DataTable table = new DataTable();
            table.Columns.Add("ProfilePic");
            table.Columns.Add("Author");
            table.Columns.Add("Gender");
            table.Columns.Add("DateJoined");
            table.Columns.Add("UserID");

            foreach (User author in searchItem)
            {
                table.Rows.Add(author.ProfilePicture, author.Author, author.Gender, author.DateJoined, author.UserID);
            }

            return table;
        }

        public DataTable booksByAuthorView(List<Book> searchItem)
        {
            DataTable table = new DataTable();
            table.Columns.Add("BookCover");
            table.Columns.Add("Title");
            table.Columns.Add("Genre");
            table.Columns.Add("QuantityInStock");
            table.Columns.Add("Price");
            table.Columns.Add("ID");
            foreach (Book book in searchItem)
            {
                table.Rows.Add(book.BookCover, book.Title, book.Genre, book.QuantityInStock, book.PricePerUnit, book.BookID);
            }

            return table;
        }

        public DataTable displayAuthorView(List<User> searchItem)
        {
            DataTable table = new DataTable();
            table.Columns.Add("ProfilePic");
            table.Columns.Add("Author");
            table.Columns.Add("Gender");
            table.Columns.Add("DateJoined");
            table.Columns.Add("UserID");

            foreach (User author in searchItem)
            {
                table.Rows.Add(author.ProfilePicture, author.Author, author.Gender, author.DateJoined, author.UserID);
            }

            return table;
        }


        public static string saveProfilePic(string fileName, string path, HttpPostedFile fil, string username)
        {
            fileName = fileName.Trim();
            path = path.Trim();
            Boolean fileOK = false;
            String fileExtension = Path.GetExtension(fileName).ToLower();
            String[] allowedExtensions = { ".jpeg", ".jpg", ".png", ".gif", ".bmp" };
            for (int i = 0; i < allowedExtensions.Length; i++)
            {
                if (fileExtension == allowedExtensions[i])
                {
                    fileOK = true;
                }
            }

            if (fileOK)
            {
                if (!(path.Length > 8000))
                {
                    FileInfo file = new FileInfo(path);

                    if (!file.Exists && !(fileName.Length > 100))
                    {
                        fil.SaveAs(path);
                        path = "ProfilePic/" + fileName;
                        int x = UserDataAccess.saveProfilePic(username, path);
                        if (x > 0)
                        {
                            return "File uploaded!";
                        }
                        else
                        {
                            return "File could not be uploaded.";
                        }
                    }
                    else
                    {
                        return "Please rename the file.";
                    }
                }
                else
                {
                    return "Error - Please call an administrator";
                }
            }
            else
            {
                return "Cannot accept files of this type.";
            }
        }

        //search
        public List<Book> searchTitle(string searchItem)
        {
            return UserDataAccess.searchTitle(searchItem);
        }

        public List<Book> GetLatestBooks()
        {
            return UserDataAccess.GetLatestBooks();
        }

        public List<Book> getAllTitles()
        {
            return UserDataAccess.GetAllTitles();
        }

        public List<Book> searchGenre(string searchItem)
        {
            return UserDataAccess.searchGenre(searchItem);
        }

        public List<User> searchAuthor(string searchItem)
        {
            return UserDataAccess.searchAuthor(searchItem);
        }

        public List<Book> booksByAuthor(string authorID)
        {
            return UserDataAccess.booksByAuthor(authorID);
        }

        public List<User> displayAuthor(string authorID)
        {
            return UserDataAccess.displayAuthor(authorID);
        }

        public List<User> getAllAuthors()
        {
            return UserDataAccess.GetAllAuthors();
        }

        public static DataTable getDetails(int id, ref int identifier, ref decimal cost, ref int availableStock, ref string title)
        {
            return UserDataAccess.getBookDetails(id, ref identifier, ref cost, ref availableStock, ref title);
        }

        public static DataTable getComments(int id)
        {
            return UserDataAccess.getAllBookComments(id);
        }

        public static DataTable getAllOrders(List<OrderItems> items, ref decimal totalPrice)
        {
            if (items.Count > 0)
            {
                DataTable table = new DataTable();
                table.Columns.Add("BookID");
                table.Columns.Add("Title");
                table.Columns.Add("Price");
                table.Columns.Add("Quantity");

                foreach (OrderItems book in items)
                {
                    table.Rows.Add(book.BookID, book.Title, book.Price, book.Quantity);
                    totalPrice += (book.Price * book.Quantity);
                }

                return table;
            }
            else
            {
                return null;
            }

        }

        public static string checkOut(int userID, string address, List<OrderItems> orders, ref int transID)
        {
            return UserDataAccess.uploadTransaction(userID, address, orders, ref transID);
        }

        public static int postComment(int userID, int bookID, int rating, string comments)
        {
            return UserDataAccess.uploadComment(userID, bookID, rating, comments);
        }

        public static bool validateCreditCard(string cardType, string cardNumber, string cardSecurityNum, string month, string year, int userID)
        {
            if ((cardNumber.Length == 12) && (cardSecurityNum.Length == 3))
            {
                try
                {
                    string salt = UserDataAccess.getSalt(userID);
                    string hashedNumber = UserDataAccess.CreatePasswordHash(cardNumber, salt);
                    string hashedSecNum = UserDataAccess.CreatePasswordHash(cardSecurityNum, salt);

                    if ((cardType == "Visa" && cardNumber.Substring(0, 6) == "440804") || (cardType == "Master Card" && cardNumber.Substring(0, 6) == "510510") || (cardType == "American Express" && cardNumber.Substring(0, 6) == "378282"))
                    {
                        if (UserDataAccess.validateCreditCard(hashedNumber, hashedSecNum, month, year, userID))
                        {
                            return true;
                        }
                        else
                        {
                            return false;
                        }
                    }
                    else
                    {
                        return false;
                    }

                }
                catch (Exception err)
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }

        public static string getFileLocation(int bookID, ref string destination)
        {
            string[] separators = { "\\" };
            string source = UserDataAccess.getFile(bookID);

            if (source != null)
            {
                string[] urlTokens = source.Split(separators, StringSplitOptions.RemoveEmptyEntries);
                if (!Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.Personal)))
                {
                    Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.Personal));
                    destination = Environment.GetFolderPath(Environment.SpecialFolder.Personal) + "\\Downloads\\" + urlTokens[urlTokens.Length - 1];
                }
                else
                {
                    destination = Environment.GetFolderPath(Environment.SpecialFolder.Personal) + "\\" + urlTokens[urlTokens.Length - 1];
                }
            }

            return source;
        }

        public static int updateStock(int book, int quantitySold)
        {
            return UserDataAccess.updateStock(book, quantitySold);
        }

        public static int updateAccount(string username, string lastname, string firstname, string email, string deliveryadd)
        {
            return UserDataAccess.updateAccount(username, lastname, firstname, email, deliveryadd);
        }


        public static int applyToBeAuthor(int userID)
        {
            return UserDataAccess.applyToBeAuthor(userID);
        }

        public static DataTable getAllDownloads(List<OrderItems> list)
        {
            DataTable table = new DataTable();
            table.Columns.Add("BookID");
            table.Columns.Add("Title");

            foreach (OrderItems book in list)
            {
                for (int aemeth = 0; aemeth < book.Quantity; aemeth++)
                {
                    table.Rows.Add(book.BookID, book.Title);
                }
            }
            return table;
        }
    }
}
